package cn.hy.batch.writer;


import cn.hy.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class ItemWriterDbDemo {

    //注入任务对象工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定,注入step对象的factory
    @Resource
    private StepBuilderFactory stepBuilderFactory;


    //创建Job对象
    @Bean
    public Job job_writer_db() {
        return jobBuilderFactory.get("job_writer_db")
                .start(step_writerDb())
                .build();
    }

    //创建Step对象
    @Bean
    public Step step_writerDb() {
        return stepBuilderFactory.get("step_writer_db")
                .<User, User>chunk(4)
                .reader(dataReader2())
                .writer(writerDb())
                .build();
    }


    @Bean
    @StepScope
    public ListItemReader<User> dataReader2() {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i + 1);
            user.setName("user-" + i);
            user.setOrderId(i + 10000);
            users.add(user);
        }
        return new ListItemReader<>(users);
    }

    @Resource
    private DataSource dataSource;

    //创建Step对象
    @Bean
    @StepScope //设定范围,避免重名bean的问题
    public JdbcBatchItemWriter<User> writerDb() {
        JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<>();
        writer.setDataSource(dataSource);
        writer.setSql("insert into user2 (id,name) values (:id,:name)");
        writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>() {
        });//Bean转换器
        return writer;
    }

}
